package com.ff.javamonkey.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Java implementation of Sha1Sum
 * @author rhama_arya
 */
public class Sha1Sum {
	// Debugging
	private final String TAG = "Sha1Sum";
	
	private byte[] sha1sum;
	private String display = null;
	private MessageDigest messageDigest;
	
	private static String convertToHex(byte[] data) {
		StringBuffer buf = new StringBuffer();
		for (byte b: data) {
			buf.append(toHex(b));
		}
		return buf.toString();
	}
	
	private static String toHex(int b) {
		return hexChr((b&0xf0)>>4)+hexChr(b&0x0f);
	}
	
	private static String hexChr(int b) {
		return Integer.toHexString(b&0xf);
	}
	
	// Return String representation of SHA1 from Text
	public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		MessageDigest md = MessageDigest.getInstance("SHA-1");
		System.out.println(text);
		byte[] sha1hash = new byte[40];
		md.update(text.getBytes("iso-8859-1"),0,text.length());
		sha1hash = md.digest();
		return convertToHex(sha1hash);
	}
	
	// Return String representation of SHA1 from File
	public static String SHA1(File file) throws NoSuchAlgorithmException, IOException {
		MessageDigest md = MessageDigest.getInstance("SHA-1");
		InputStream is = new FileInputStream(file);
		byte[] buffer = new byte[8192];
		byte[] sha1hash = new byte[40];
		do {
			int read = is.read(buffer);
			if (read <= 0) break;
			md.update(buffer,0,read);
		} while (true);
		sha1hash = md.digest();
		return convertToHex(sha1hash);
	}
}
